package com.byzk.p2p.front.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.byzk.p2p.admin.base.controller.BaseController;
import com.byzk.p2p.admin.base.util.DateUtils;
import com.byzk.p2p.admin.base.util.JsonMsg;
import com.byzk.p2p.admin.base.util.PageInfo;
import com.byzk.p2p.admin.borrow.dto.Borrow;
import com.byzk.p2p.admin.borrow.dto.BorrowApply;
import com.byzk.p2p.admin.borrow.dto.ChangeRecord;
import com.byzk.p2p.admin.borrow.service.BorrowService;
import com.byzk.p2p.admin.borrow.service.ChangeService;
import com.byzk.p2p.admin.borrow.service.TenderService;
import com.byzk.p2p.admin.borrow.vo.ChangeVo;
import com.byzk.p2p.admin.fuiou.controller.FuionAccountController;
import com.byzk.p2p.admin.user.dto.User;
import com.byzk.p2p.admin.user.dto.UserAccount;
import com.byzk.p2p.admin.user.service.UserAccountService;
import com.byzk.p2p.admin.user.service.UserAuthService;
import com.byzk.p2p.admin.user.service.UserService;

/**
 * 债权转让
 * @author suker.zhou
 *
 */

@Controller
@RequestMapping("/change")
@Scope("prototype")
public class FrontChangeController extends BaseController{
	
	@Autowired
	private UserService userService;
	@Autowired
	private ChangeService changeService;
	@Autowired
	private UserAccountService accountService;
	@Autowired
	private BorrowService borrowService;
	@Autowired
	private TenderService tenderService;
	@Autowired
	private FuionAccountController fuionAccountController;
//	@Autowired
//	private UserAccountService userAccountService ; 
//	@Autowired
//	private UserAuthService userAuthService ;

	/**
	 * 债权转让明细
	 * @param id 债权转让id
	 * @return
	 */
	@RequestMapping(value="/detail")
	public ModelAndView changeDetail(@RequestParam int id,Model model){
		User user = (User) session.getAttribute("_user");
		user = userService.getById(user == null ?0:user.getId());
	
		ChangeVo changeVo = changeService.getChange(id);
		//转让记录
		List<ChangeRecord> list = changeService.listByChangeId(id);
		//用户账户
		if(user!=null){
			model.addAttribute("userAccount", accountService.getByUserId(user.getId()));
		}
		model.addAttribute("model", changeVo);
		model.addAttribute("list", list);
		model.addAttribute("user", user);
		return new ModelAndView("/front/change/detail");
	}
	
	/**
	 * 债权购买
	 * @param changeId 转让id
	 * @throws Exception
	 */
	@RequestMapping(value="/save",method=RequestMethod.GET)
	public void saveUserChange(@RequestParam("changeId") Integer changeId) throws Exception{
		User frontUser = (User) session.getAttribute("_user");
		frontUser = userService.getById(frontUser == null ?0:frontUser.getId());
		try {
			ChangeVo changeVo = changeService.getChange(changeId);
			if (changeVo == null) {
				printJSON(new JsonMsg(1, "转让失败！"));
				return;
			}
			if(!"T".equals(changeVo.getStatus())){
				printJSON(new JsonMsg(1, "状态异常，无法转让!"));
				return;			
			}			
			if("Y".equals(changeVo.getStatus())){
				printJSON(new JsonMsg(1, "转让已完成！"));
				return;			
			}

			Borrow borrow=borrowService.detailBorrow(changeVo.getBorrowId());
			BorrowApply apply=borrowService.getBorrowApply(borrow.getBorrowApplyId());
			if(apply.getUserId().equals(frontUser.getId())){
				printJSON(new JsonMsg(1, "自己不能回购自己借款的标！"));
				return;				
			}
			if(changeVo.getUserId().equals(frontUser.getId())){
				printJSON(new JsonMsg(1, "不能购买自己发布的债权！"));
				return;				
			}			
			UserAccount account=accountService.getByUserId(frontUser.getId());
			if(account.getBalance()<changeVo.getMin()){
				printJSON(new JsonMsg(1, "您的迅泊达可用余额为￥"+account.getBalance()+"元,请先充值！"));
				return;				
			}
			
			//查询金账户用户可用余额
			UserAccount accountFY = fuionAccountController.getFuionAccountBalance(frontUser);
			if(accountFY.getBalance() < changeVo.getMin() ){
				printJSON(new JsonMsg(1, "您的金账户可用余额为￥"+accountFY.getBalance()+"元,请先充值！"));
				return ;
			}
			
			if (DateUtils.getDistanceTimeNum(new Date(), changeVo.getOverdue())>=0) {
				printJSON(new JsonMsg(1, "已超过到期时间，转让失败！"));
				return;
			}
//			Date expireDate = null;
//			if(null!=changeVo.getUpdateTime()){
//				expireDate = changeVo.getUpdateTime();
//			}else{
//				expireDate = changeVo.getCreateTime();
//			}
			if (DateUtils.betweenDays(changeVo.getCreateTime(), new Date())>3) {
				printJSON(new JsonMsg(1, "距发布时间已超过3天，转让失败！"));
				return;
			}
			
			/*
			int i = changeService.buyChange(frontUser.getId(),changeId);
			
			UserTender tender=tenderService.getById(changeVo.getTenderId());
			tender.setChanges("Y");
			tenderService.saveOrUpdate(tender);
			*/
			printJSON(new JsonMsg(-1, "债权购买成功！"));
		} catch (Exception e) {
			e.printStackTrace();
			printJSON(new JsonMsg(0, "系统异常,请稍后再试！"));
		}
		
	}
	
	@RequestMapping(value="/list")
	public ModelAndView changeList(Model model,
			 		@RequestParam(value="index",required=false,defaultValue="1") int index,
				    @RequestParam(value="limit",required=false,defaultValue="10") int limit,
				    @RequestParam(value="status",required=false,defaultValue="all") String status) throws Exception{
		//累计投资金额
		Double totalTenderAmount = tenderService.getAllTenderAmount(null,null);
		//赚取收益
		Double income=tenderService.getAllRecovedInterest();
		//总借款成功标数量
		Integer count=borrowService.countAll();
		//债权转让
		ChangeVo changeVo = new ChangeVo();
		if(!"all".equals(status)){
			changeVo.setStatus(status);
		}
		PageInfo<ChangeVo> pageInfo = changeService.listChange(index, limit, changeVo);
		model.addAttribute("status", status);
		model.addAttribute("totalTenderAmount", totalTenderAmount);
		model.addAttribute("income", income);
		model.addAttribute("count", count);
		model.addAttribute("pageInfo", pageInfo);
		return new ModelAndView("/front/change/list");
	}
}
